package main

import (
	"strings"
	"time"

	"../logger"
	"../util"
)

type Condition struct {
	// key string
	op  string
	val string
}

func parseConds(conds []string) map[string][]Condition {
	if len(conds) == 0 {
		return nil
	}
	// condList := make([]Condition, 0)
	ret := make(map[string][]Condition, 0)
	cnd := Condition{op: "", val: ""}
	index := -1
	for _, cond := range conds {
		if strings.Index(cond, ">") > 0 {
			index = strings.Index(cond, ">")
		} else if strings.Index(cond, "=") > 0 {
			index = strings.Index(cond, "=")
		} else if strings.Index(cond, "<") > 0 {
			index = strings.Index(cond, "<")
		} else {
			logger.Errorf("Parse query condition error: " + cond)
			return nil
		}
		cndkey := cond[0:index]
		cnd.op = cond[index : index+1]
		cnd.val = cond[index+1:]
		ret[cndkey] = append(ret[cndkey], cnd)
	}
	return ret
}

func parseDateTime(conds map[string][]Condition) (time.Time, time.Time, error) {
	min := ""
	max := ""
	var mintime time.Time
	var maxtime time.Time
	var err error
	dateConds := conds["DATETIME"]
	for _, cond := range dateConds {
		if cond.op == ">" {
			min = cond.val
		}
		if cond.op == "<" {
			max = cond.val
		}
	}
	if min == "" && max == "" {
		logger.Errorln("No DATETIME limit, query datas in last three months")
		mintime = time.Now().AddDate(0, -3, 0)
		maxtime = time.Now()
		return mintime, maxtime, nil
	} else if min == "" || max == "" {
		logger.Errorln("Lack either lower bound or upper bound of DATETIME")
		return mintime, maxtime, util.ParseArgsErr
	}
	mintime, err = time.Parse("20060102150405000", min)
	if err != nil {
		logger.Errorln("Parse time error: " + min)
		return mintime, maxtime, err
	}
	maxtime, err = time.Parse("20060102150405000", max)
	if err != nil {
		// parse time error
		logger.Errorln("Parse time error: " + max)
		return mintime, maxtime, err
	}
	return mintime, maxtime, nil
}

func mergeResult(a []map[string]string, b []map[string]string) []map[string]string {
	cur := make([]map[string]string, len(a)+len(b))
	copy(cur, a)
	copy(cur[len(a):], b)
	return cur
}

// format: ["2006-01-02"]
func getDates(lower time.Time, upper time.Time) []string {
	var datelist []string
	cur := lower
	date := cur.Format("2006-01-02")
	for {
		if cur.After(upper) {
			break
		}
		datelist = append(datelist, date)
		cur = cur.AddDate(0, 0, 1)
		date = cur.Format("2006-01-02")
	}
	return datelist
}

// format:20060102030405000
func Time2Unix(t string) (int64, error) {
	_time, err := time.Parse("20060102150405000", t)
	if err != nil {
		// parse time error
		logger.Errorln("Parse time error: " + t)
		return 0, err
	}
	return _time.UnixNano(), nil
}
